import {
  VuexModule,
  Module,
  Mutation,
  getModule,
  Action
} from "vuex-module-decorators";
import store from "@/store";
import { menuConfig } from "@/config/menuConfig";
import { ASideDataType } from "ASideTypes";
import { isEmpty, isUndefined, isEqual, isLength, concat } from "lodash";

export interface HeadModuleType {
  list: Array<{ toPath: string; title: string }>;
}

type PathType = Pick<ASideDataType, "name" | "title">;

@Module({ dynamic: true, name: "head", store })
export default class Head extends VuexModule {
  private _list: Array<PathType> = [];

  get listPathHeader(): Array<PathType> {
    return this._list;
  }

  @Mutation
  SET_TO_PATH(payload: PathType) {
    // 这里的this就是指当前的 state，
    // 这里的this._list 就是指 state 中的 _list
    this._list.push(payload);
  }

  /**
   * 这里遍历 menuConfig，有延时，需要使用action。
   */
  @Action({ commit: "SET_TO_PATH" })
  UpdateNav(name: string | null | undefined) {
    if (isEmpty(name) || isUndefined(name)) return;

    let result!: PathType;

    menuConfig.forEach(item => {
      if (isEqual(item.name, name)) {
        const { name, title } = item;
        result = { name, title };
      } else if (!isUndefined(item.children)) {
        item.children.forEach(itemChild => {
          if (isEqual(itemChild.name, name)) {
            result = {
              name: itemChild.name,
              title: `${item.title}/${itemChild.title}`
            };
          }
        });
      }
    });

    if (!isUndefined(result) || !isEmpty(result)) return result;
  }
}

export const HeadModule = getModule(Head);
